package dfs;

public class NumberOfEnclaves1020 {
    public int numEnclaves(int[][] grid) {
        int result = 0;
        if (grid.length == 0) {
            return result;
        }

        for (int i = 0; i < grid.length; i++) {
            if (grid[i][0] == 1) {
                dfs(i, 0, grid);
            }
            if (grid[i][grid[0].length - 1] == 1) {
                dfs(i, grid[0].length - 1, grid);
            }
        }

        for (int i = 0; i < grid[0].length; i++) {
            if (grid[0][i] == 1) {
                dfs(0, i, grid);
            }
            if (grid[grid.length - 1][i] == 1) {
                dfs(grid.length - 1, i, grid);
            }
        }


        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    result++;
                }
            }
        }
        return result;
    }

    private void dfs(int i, int j, int[][] grid) {
        if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == 1) {
            grid[i][j] = -1;
            dfs(i + 1, j, grid);
            dfs(i - 1, j, grid);
            dfs(i, j - 1, grid);
            dfs(i, j + 1, grid);
        }

    }
}
